<!--
 * @Description:
 * @Author: zheng yiliang
 * @Date: 2021-03-15 20:58:52
 * @LastEditTime: 2021-06-11 11:38:34
 * @LastEditors: zheng yiliang
-->
<template>
  <div class="article-table">
    <el-table v-loading="loading" :data="articleData">
      <el-table-column label="标题" class-name="article_title">
        <template #default="{ row }">
          <el-badge value="新消息" v-if="newMessage(row.comments)">
            {{ row.title }}
          </el-badge>
          <span v-else>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者"> </el-table-column>
      <el-table-column prop="keyword" label="关键字"></el-table-column>
      <el-table-column label="封面">
        <template #default="{ row }">
          <img
            :src="row.img_url"
            width="40px"
            height="40px"
            style="border-radius: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column label="标签" width="120">
        <template #default="{ row }">
          <span v-for="(item, index) in row.tags" :key="item._id"
            >{{ item.name
            }}<i v-show="index !== row.tags.length - 1" class="mglr5"
              >|</i
            ></span
          >
        </template>
      </el-table-column>
      <el-table-column label="分类">
        <template #default="{ row }">
          <el-tag type="success" v-for="item in row.category" :key="item._id">{{
            item.name
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-tag :type="row.state ? 'success' : 'info'">{{
            row.state ? '已发布' : '草稿'
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="meta" label="观看/评论" width="120">
        <template #default="{ row }">
          {{ row.meta.views }}<i class="mglr5">|</i>
          <!-- {{ row.meta.likes }}<i class="mglr5">|</i > -->
          <!-- <el-badge value="new" v-if="comments.length && isRead">
            <i class="comments" @click="handleDetail(row)">{{
              row.meta.comments
            }}</i>
          </el-badge> -->
          <i class="comments" @click="handleDetail(row)">{{
            row.meta.comments
          }}</i>
        </template>
      </el-table-column>
      <el-table-column prop="origin" label="原创状态">
        <template #default="{ row }">
          <el-tag :type="$options.filters['tagType'](row.origin)">{{
            row.origin | originFilter
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150">
        <template #default="{ row }">
          {{ row.create_time | formatDate }}
        </template>
      </el-table-column>
      <el-table-column width="140px" label="操作" align="center">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="editArticle(row._id)"
          >
            修改
          </el-button>
          <el-button
            @click="deleteArticle(row._id)"
            size="mini"
            type="text"
            icon="el-icon-delete"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :background="true"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <el-dialog append-to-body :visible.sync="dialogVisible" width="80%">
      <el-button
        @click="allRed"
        style="margin: 0px 0px 10px 0px; padding: 6px 10px"
        type="danger"
        v-if="comments.length && isRead"
        >一键已读</el-button
      >
      <ul class="blog-comment" id="blog-comment">
        <template v-if="comments.length">
          <li v-for="(item, i) in comments" :key="i">
            <div class="comment-parent">
              <el-avatar
                style="position: absolute"
                class="header-img"
                :size="40"
                :src="item.headImg"
              ></el-avatar>

              <div class="info">
                <span class="username">{{ item.name }}</span>
                <span class="blogger" v-if="item.type === 0">站长</span>
                <el-button
                  v-if="item.is_handle !== 2"
                  type="text"
                  class="btn-reply"
                  >已读</el-button
                >
                <el-button
                  style="color: #f56c6c"
                  class="btn-reply"
                  v-else
                  type="text"
                  @click="handleRead(item)"
                  >标记为已读</el-button
                >
                <el-button
                  type="text"
                  class="btn-reply"
                  @click="handleDelete(item)"
                  >删除</el-button
                >
              </div>
              <div class="comment-content">
                <p>{{ item.comment }}</p>
              </div>
              <p class="info info-footer">
                <span class="comment-time">{{ item.time | dateFormate }}</span>
                <el-button
                  type="text"
                  v-if="_inputShow(i)"
                  class="btn-reply"
                  @click="hideReplyInput(i, item.name, item.id)"
                  >收起</el-button
                ><el-button
                  type="text"
                  v-else
                  class="btn-reply"
                  @click="showReplyInput(i, item.name, item.id)"
                  >回复</el-button
                >
              </p>
            </div>
            <div v-show="item.reply.length" class="line-hr"></div>
            <div
              class="comment-child"
              v-for="(reply, j) in item.reply"
              :key="j"
            >
              <el-avatar
                style="position: absolute"
                class="header-img"
                :size="40"
                :src="reply.fromAvatar"
              ></el-avatar>
              <div class="info">
                <span class="username">{{ reply.from }}</span>
                <span class="blogger" v-if="reply.fromType === 0">站长</span>
                <span style="padding-right: 5px">回复</span>
                <span class="username">{{ reply.to }}</span>
                <span>{{ reply.comment }}</span>
              </div>
              <p class="info">
                <span class="comment-time">{{
                  reply.create_time | dateFormate
                }}</span>
                <el-button
                  type="text"
                  v-if="_inputChildShow(i, j)"
                  class="btn-reply"
                  @click="hideReplyInput(i, reply.from, reply.fromId, j)"
                  >收起</el-button
                ><el-button
                  type="text"
                  v-else
                  class="btn-reply"
                  @click="showReplyInput(i, reply.from, reply.fromId, j)"
                  >回复</el-button
                >
                <el-button
                  v-if="reply.is_handle !== 2"
                  type="text"
                  class="btn-reply"
                  >已读</el-button
                >
                <el-button
                  style="color: #f56c6c"
                  class="btn-reply"
                  v-else
                  type="text"
                  @click="handleReplyRead(reply, item._id)"
                  >标记为已读</el-button
                >
                <el-button
                  type="text"
                  class="btn-reply"
                  @click="delReplyComment(reply._id, item._id, item)"
                  >删除</el-button
                >
              </p>
              <div class="replycontainer" v-show="_inputChildShow(i, j)">
                <el-form>
                  <el-form-item>
                    <el-input
                      v-model="replyComment"
                      :rows="3"
                      type="textarea"
                      :placeholder="`回复${reply.from}：${reply.comment}`"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button
                      @click="sendCommentReply(reply, item)"
                      type="primary"
                      class="layui-btn layui-btn-xs"
                    >
                      提交
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <div class="replycontainer" v-show="_inputShow(i)">
              <el-form>
                <el-form-item>
                  <el-input
                    :rows="3"
                    v-model="replyComment"
                    type="textarea"
                    :placeholder="`回复${item.name}：${item.comment}`"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    @click="sendCommentReply(item)"
                    type="primary"
                    class="layui-btn layui-btn-xs"
                  >
                    提交
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </li>
        </template>
        <template v-else> 暂无评论... </template>
      </ul>
    </el-dialog>
  </div>
</template>

<script>
const publicMap = {
  1: '公开',
  2: '私密'
}

const statusMap = {
  1: '已发布',
  2: '草稿'
}
import {
  commentsByArticle,
  replyComments,
  delComment,
  delReplyComment,
  replyRead,
  read,
  allRead
} from '@/api/article'
import { mapGetters } from 'vuex'
export default {
  props: {
    articleData: {
      type: Array,
      default: () => []
    },
    currentPage: {
      type: Number,
      default: 0
    },
    pageSize: {
      type: Number,
      default: 10
    },
    total: {
      type: Number,
      default: 0
    }
  },
  filters: {
    dateFormate(date) {
      // 获取js 时间戳
      date = new Date(date).getTime()
      let time = new Date().getTime()
      // 去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000)
      // 存储转换值
      let s
      if (time < 60 * 10) {
        // 十分钟内
        return '刚刚'
      } else if (time < 60 * 60 && time >= 60 * 10) {
        // 超过十分钟少于1小时
        s = Math.floor(time / 60)
        return s + '分钟前'
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        // 超过1小时少于24小时
        s = Math.floor(time / 60 / 60)
        return s + '小时前'
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        // 超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24)
        return s + '天前'
      } else {
        // 超过30天ddd
        date = new Date(parseInt(date))
        return (
          date.getFullYear() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getDate()
        )
      }
    },
    originFilter(val) {
      if (val === 0) return '原创'
      if (val === 1) return '转载'
      if (val === 2) return '混合'
      return '未知'
    },
    tagType(val) {
      if (val === 0) return 'danger'
      if (val === 1) return 'success'
      if (val === 2) return 'warning'
      return 'primary'
    }
  },
  data() {
    return {
      comment: '',
      replyComment: '',
      comments: [],
      currentId: '',
      dialogVisible: false,
      loading: false,
      publicMap,
      statusMap,
      rowArticle: ''
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar']),
    isRead() {
      let flag = false
      this.comments.forEach((item) => {
        if (item.is_handle === 2) {
          flag = true
        }
        item.reply.forEach((ele) => {
          if (ele.is_handle === 2) {
            flag = true
          }
        })
      })
      console.log(flag)
      return flag
    }
  },
  methods: {
    newMessage(rows) {
      let len = rows.filter((item) => item.is_handle === 2).length
      let chLen = false
      rows.forEach((item) => {
        if (item.reply.filter((ele) => ele.is_handle === 2).length) {
          chLen = true
        }
      })
      return len || chLen
    },
    async allRed() {
      console.log(this.rowArticle)
      const { _RejCode } = await allRead({ article_id: this.currentId })
      if (_RejCode !== '00000000') return
      await this.$nextTick()
      this.comments.forEach((item) => {
        item.is_handle = 1
        item.reply.forEach((ele) => (ele.is_handle = 1))
      })
    },
    async handleRead(row) {
      const { _RejCode } = await read({ _id: row._id })
      if (_RejCode !== '00000000') return
      row.is_handle = 1
    },
    handleDelete(row) {
      this.$confirm('是否确认删除评论人为"' + row.name + '"的评论?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return delComment({ id: row._id, article_id: this.currentId })
        })
        .then((res) => {
          console.log(this.rowArticle)
          this.rowArticle.meta.comments -= 1
          // this.getList()
          this.comments = this.comments.filter((item) => item._id !== row._id)
          this.$message.success(res._RejMsg)
        })
    },
    async handleReplyRead(reply, _id) {
      const { _RejCode } = await replyRead({ replyId: reply._id, _id })
      if (_RejCode !== '00000000') return
      reply.is_handle = 1
    },
    delReplyComment(replyId, id, row) {
      this.$confirm('是否确认删除此评论?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function () {
          return delReplyComment({ replyId, _id: id })
        })
        .then((res) => {
          row.reply = row.reply.filter((item) => item._id !== replyId)
          this.$message.success(res._RejMsg)
        })
    },
    showReplyInput(i, name, id, j) {
      this.replyComment = ''
      this.comments.forEach((item) => {
        item.inputShow = false
        item.reply.forEach((item) => {
          item.inputShow = false
        })
      })
      if (j === undefined) {
        this.comments[i].inputShow = !this.comments[i].inputShow
      } else {
        this.comments[i].inputShow = false
        this.comments[i].reply[j].inputShow =
          !this.comments[i].reply[j].inputShow
      }
    },
    hideReplyInput(i, name, id, j) {
      this.replyComment = ''
      this.comments.forEach((item) => {
        item.inputShow = false
        item.reply.forEach((item) => {
          item.inputShow = false
        })
      })
    },
    _inputShow(i) {
      return this.comments[i].inputShow
    },
    _inputChildShow(i, j) {
      return this.comments[i].reply[j].inputShow
    },
    async sendCommentReply(comment, item) {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '评论不能为空'
        })
        return
      }
      const reply = {
        from: this.name,
        fromAvatar: this.avatar,
        to: comment.name || comment.from,
        toId: comment.id || comment.fromId,
        toAvatar: comment.headImg || comment.fromAvatar,
        comment: this.replyComment,
        _id: item ? item._id : comment._id
      }
      const { _RejCode, data, _RejMsg } = await replyComments(reply)
      if (_RejCode !== '00000000') {
        this.$message({
          showClose: true,
          type: 'error',
          offset: '80',
          message: _RejMsg
        })
        return
      }
      this.replyComment = ''
      this.allComments()
      console.log(data)
    },
    dateStr(date) {
      // 获取js 时间戳
      let time = new Date().getTime()
      // 去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000)
      // 存储转换值
      let s
      if (time < 60 * 10) {
        // 十分钟内
        return '刚刚'
      } else if (time < 60 * 60 && time >= 60 * 10) {
        // 超过十分钟少于1小时
        s = Math.floor(time / 60)
        return s + '分钟前'
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        // 超过1小时少于24小时
        s = Math.floor(time / 60 / 60)
        return s + '小时前'
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        // 超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24)
        return s + '天前'
      } else {
        // 超过30天ddd
        date = new Date(parseInt(date))
        return (
          date.getFullYear() +
          '/' +
          (date.getMonth() + 1) +
          '/' +
          date.getDate()
        )
      }
    },
    async allComments() {
      const { _RejCode, data } = await commentsByArticle(this.currentId)
      if (_RejCode !== '00000000') return
      console.log(data)
      this.comments = data
    },
    handleDetail(row) {
      console.log(row)
      this.currentId = row._id
      this.comments = []
      this.dialogVisible = true
      this.rowArticle = row
      this.allComments()
    },
    handleCurrentChange(page) {
      this.$emit('handleCurrentPage', page)
    },
    handleSizeChange(size) {
      this.$emit('handleCurrentSize', size)
    },
    // 编辑文章
    editArticle(val) {
      this.$emit('handleEdit', val)
    },

    // 设文章为 公开 / 私密
    setArticlePrivate(val) {},
    // 删除文章
    deleteArticle(val) {
      this.$emit('handleRemove', val)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .article_title {
  .cell {
    overflow: initial !important;
  }
  .el-badge__content {
    line-height: 15px;
  }
}
.mglr5 {
  margin: 0px 5px;
}
.comments {
  cursor: pointer;
  color: #00b672;
  font-style: normal;
}
.blog-comment {
  margin: 0px;
  padding-left: 0px;
  .el-button {
    padding-top: 5px;
    padding-bottom: 5px;
  }
  li {
    list-style: none;
    border-bottom: 1px dotted #bbb;
    padding: 15px 0 10px 0;
    &:first-child {
      border-top: 1px dotted #bbb;
    }
  }
  .blogger {
    display: inline-block;
    padding: 2px 5px;
    margin: 0px 5px;
    color: #fff;
    background: #6bc30d;
    border-radius: 3px;
    line-height: 16px;
    font-size: 12px !important;
  }
  .line-hr {
    border-top: 1px dotted #bbb;
    height: 1px;
    margin: 10px 0;
    margin-left: 53px;
  }
  .el-avatar {
    img {
      width: 40px !important;
      height: 100% !important;
    }
  }

  .el-form-item {
    margin-bottom: 2px;
  }
  .btn-reply {
    padding: 0px;
    font-size: 13px;
  }
  .blog-editor {
    .el-form-item {
      margin-top: 16px;
    }
  }
  .comment-content,
  .info,
  .replycontainer {
    margin-left: 53px;
  }
  .info-footer {
    font-size: 13px;
  }

  .blog-comment .info span {
    padding-right: 5px;
  }

  .info .username {
    color: #01aaed;
    margin-right: 5px;
  }
  .info .btn-reply {
    color: #009688;
    margin-left: 10px;
  }
  .comment-content {
    padding: 2px 0 5px 0;
    min-height: 30px;
    font-size: 13px;
    word-break: break-all;
  }

  .comment-parent > img {
    width: 45px;
    height: 45px;
    margin: 5px 5px 5px 0;
    position: absolute;
    border-radius: 50px;
  }
  .comment-child > img {
    width: 40px;
    height: 40px;
    margin: 5px 5px 5px 0;
    position: absolute;
    border-radius: 50px;
  }
  .comment-child {
    margin-left: 53px;
    min-height: 50px;
  }
  .comment-child .info {
    margin-left: 48px;
    font-size: 12px;
    line-height: 20px;
  }
}
</style>
